package com.wzt.consumer.service.impl;

import com.wzt.base.util.AjaxResponse;
import com.wzt.base.util.SendSmsUtil;
import com.wzt.base.util.VerificationCodeUtil;
import com.wzt.base.util.VerificationImage;
import com.wzt.consumer.domain.LoginInfo;
import com.wzt.consumer.dto.SmsCodeRegisterDto;
import com.wzt.consumer.mapper.LoginInfoMapper;
import com.wzt.consumer.service.IVerificationCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author Zenith
 */
@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Value("${smsCode.register.resend-time}")
    private Integer resendTime;

    @Value("${smsCode.register.expire-time}")
    private Integer expireTime;

    @Override
    public String getImageCode(String key) throws IOException {
        //生成4为验证码
        String verifyCode = VerificationImage.generateVerifyCode(4);
        //验证吗放入redis，并且3分钟过期时间
        redisTemplate.opsForValue().set("imgVerifyCode_" + key, verifyCode, 3, TimeUnit.MINUTES);
        //把验证码合成图片并加密为base64数据进行返回
        String base64Data = VerificationImage.VerifyCode(100, 40, verifyCode);
        return base64Data;
    }

    @Override
    public AjaxResponse sendRegisterSmsCode(SmsCodeRegisterDto smsCodeDto) {
        String mobile = smsCodeDto.getMobile();
        String imageCodeKey = smsCodeDto.getImageCodeKey();
        String imageCode = smsCodeDto.getImageCode();

        //1 校验
        //1.0 空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(imageCodeKey) || StringUtils.isEmpty(imageCode)) {
            return AjaxResponse.oneResponse().setSuccess(false).setMessage("非法请求，参数异常！");
        }
        //1.1 判断图片验证码是否正确
        String imageCodeOfRedis = (String) redisTemplate.opsForValue()
                .get("imgVerifyCode_" + imageCodeKey);
        if (!imageCode.trim().equalsIgnoreCase(imageCodeOfRedis)) {
            return AjaxResponse.oneResponse().setSuccess(false).setMessage("请输入正确图片验证码！");
        }
        //1.2 判断手机号是否已经被注册
        LoginInfo logininfo = loginInfoMapper.loadUserByMobile(mobile);
        if (logininfo != null) {
            return AjaxResponse.oneResponse().setSuccess(false).setMessage("该手机号已经被注册！请登录后使用！");
        }

        //2 判断原来的验证码是否存在
        String key = "register_sms_code_" + mobile;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue()
                .get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {
            //2.1 如果不存在就产生新的
            code = VerificationCodeUtil.getRandomString(6);
        } else {
            //2.2 如果存在，判断是否已过重发时间，如果没有过报错，过了直接原来的
            code = smsCodeOfRedis.split(":")[0];
            String time = smsCodeOfRedis.split(":")[1];
            if (System.currentTimeMillis() - new Date(Long.valueOf(time)).getTime() <= 60 * 1000 * resendTime) {
                return AjaxResponse.oneResponse().setSuccess(false).setMessage("非法请求，请勿乱搞！");
            }
        }


        //3 记录验证码到redis
        redisTemplate.opsForValue().set(key, code + ":" + System.currentTimeMillis(), expireTime, TimeUnit.MINUTES);


        //4 调用短信接口进行发送
        String content = String.format("你的验证码为%s,请在%s分钟之内使用！", code, expireTime);
        SendSmsUtil.sendSms(mobile, content);
        System.out.println("已经成功发送了一条短信,内容为" + content);

        //5 记录发送记录 @TODO
        return AjaxResponse.oneResponse();
    }
}
